package arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 在排序数组中查找元素的第一个和最后一个位置
 * User: Li_yizYa
 * Date: 2025/9/2
 * Time: 21:56
 */
public class Solution8 {
    public static int[] function(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        // 寻找到第一个等于target的数，和第一个大于target的数
        int left = binarySearch(nums, target, true);
        int right = binarySearch(nums, target, false) - 1;
        if (left <= right && right < nums.length && nums[left] == target && nums[right] == target) {
            return new int[]{left, right};
        }
        return new int[]{-1, -1};
    }
    private static int binarySearch(int[] nums, int target, boolean flag) {
        int left = 0;
        int right = nums.length - 1;
        int ret = Integer.MIN_VALUE;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] > target || (flag && nums[mid] >= target)) {
                right = mid - 1;
                ret = mid;
            } else {
                left = mid + 1;
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {5, 7, 7, 8, 8, 10};
        int[] ret = function(nums, 7);
        for (int i : ret) {
            System.out.println(i);
        }
    }
}
